<?php

namespace app\agentapi\controller\user;

use app\agentapi\controller\Controller;
use think\Session;
use think\Cache;
use app\admin\model\BaseSetting as SettingModel;
use think\Db;
use think\Image;
use OSS\OssClient;
use app\admin\model\article\UploadFile;
use app\agentapi\model\Sms;
use app\common\library\WsgtLog;
use app\common\service\qrcode\Gifts as GiftsModel;
/**
 * 客户相关
 */
class User extends Controller{
    private $config;
    public function _initialize(){
        //parent::_initialize();
        // 存储配置信息
        $this->config = SettingModel::getItem('storage');
    }

    /**
     * 生成小程序二维码
     */
    public function qrcode(){
        //商品详情
        $user_id=input('post.user_id');
        $show=input('post.show');
        if(empty($user_id)){
            return json(['msg'=>'user_id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($show)){
            return json(['msg'=>'显示状态不能为空','code'=>'error','data'=>[]]);
        }
        $GiftsModel=new GiftsModel();
        $detail = $GiftsModel->getImage($user_id,$show);
        return json(['msg'=>'获取二维码链接成功','code'=>'success','data'=>$detail]);
    }
    /**
     * 客户主页/获取客户列表
     */
   public function index(){
       $log = WsgtLog::instance();
       $log->setFilename('kehu/list');
       $userId=input('post.userId');//当前登录人id
       $userInfo=Db::name('yonghui_user')->where(['id'=>$userId])->find();
       $log->info($userInfo, '当前登录人信息');
       //待跟进  已跟进  visitTime>当前时间戳  或者0 表示未跟进，visitTime<当前时间戳 且不为0 表示已跟进。
       $genjinStatus=input('post.genjinStatus');//1 待跟进  2 已跟进
       //客户状态  跟进中  已买  已签约  已失效  followStatus  1:跟进中 2：已失效 3：已买 4：已签约
       $status=input('post.status');
       $paixu=input('post.paixu');//跟进排序 1 正序  2倒序   根据visitTime排序
       if($genjinStatus!=1&&$genjinStatus!=2){
           return json(['msg'=>'跟进参数不正确','code'=>'error','data'=>[]]);
       }
       $order=['id'=>'desc'];
       if($genjinStatus){
           if($genjinStatus==1){
               //待跟进
               $where['visitTime']=[['=',0],['<',time()],'or'];
           }else{
               //已跟进
               $where['visitTime']=['>',time()];
           }
           $where['followStatus']=['=',1];
       }
       if($paixu){
           if($paixu==1){
               $order=['createTime'=>'asc'];
           }else{
               $order=['createTime'=>'desc'];
           }
       }else{
           $order=['createTime'=>'desc'];
       }
       if($status){
           $where['followStatus']=['=',$status];
           if($status!=1){
               unset($where['visitTime']);
           }else{
               $daofangStatus=input('post.daofangStatus');//1 未到访  2 已到访

              // $daofangStatus=1;//去掉  TODO
               if(empty($daofangStatus)){
                   return json(['msg'=>'请选择到访状态','code'=>'error','data'=>[]]);
               }
               $where['daofangStatus']=['=',$daofangStatus];
           }
       }
       //客户姓名/电话   name|phone
       $search=input('post.search');
       if($search){
           $where['name|phone']=['like','%'.$search.'%'];
       }
       //录入时间段  createTime
       $lutimeStart=input('post.luruTimeStart');
       $lutimeEnd=input('post.luruTimeEnd');
       if($lutimeStart&&$lutimeEnd){
           $where['createTime']=['between',[strtotime($lutimeStart),strtotime($lutimeEnd)+86399]];
       }
       if($lutimeStart&&!$lutimeEnd){
           $where['createTime']=['>=',strtotime($lutimeStart)];
       }
       if(!$lutimeStart&&$lutimeEnd){
           $where['createTime']=['<=',strtotime($lutimeEnd)+86399];
       }
       //意向楼盘id  propertiesId
       $propertiesId=input('post.propertiesId');
       if($propertiesId){
           $where['propertiesId']=['=',$propertiesId];
       }
       //驻场可以看见项目组所有置业顾问，渠道销售录入的客户/置业顾问可以看见驻场分配给自己和自己录入的客户/渠道销售可以看见自己录入的客户。
       $userIds=[];
       if($userInfo['type']==1){
           //驻场人员
           //查询驻场所属的自营公司、、查询自营公司下所有渠道公司。。查询所有渠道公司对应的员工id,,与驻场管辖的楼盘id且
           //根据当前驻场所属项目组确定 楼盘id
            /*$bInfo=Db::name('yonghui_building')->where(['projectId'=>$userInfo['projectId']])->field('id,projectId')->select();
            $bui=[];
            foreach($bInfo as $k=>$v){
                $bui[]=$v['id'];
            }*/
           if($userInfo['loupanids']=='all'){
               $bInfo=Db::name('yonghui_building')->where(['q'=>$userInfo['projectId']])->field('id,projectId')->select();
               $bui=[];
               foreach($bInfo as $k=>$v){
                   $bui[]=$v['id'];
               }
               $where['propertiesId']=['in',$bui];
           }else{
               $where['propertiesId']=['=',$userInfo['loupanids']];
           }
       }elseif($userInfo['type']==2){
           //置业顾问
           $where['inputId|followUserId']=['=',$userId];
       }elseif($userInfo['type']==3){
           //渠道销售人员
           $where['inputId']=['=',$userId];
       }elseif($userInfo['type']==4){
           //渠道经理，获取所有直属渠道公司
           $soucomId=input('post.sourceId');
           $qudaoUserId=input('post.qudaoUserId');
           if($soucomId){
               $where['sourceId']=['=',$soucomId];
               if($qudaoUserId){
                   $where['inputId']=['=',$qudaoUserId];
               }
           }else{
               //获取所有渠道公司
               $companyInfo1=Db::name('yonghui_company')->where(['userId'=>$userId,'type'=>2])->select()->toArray();
               if(!empty($companyInfo1)){
                   foreach($companyInfo1 as $k=>$v){
                       $userList[]=$v['id'];
                   }
               }else{
                   $userList=[];
               }
               $where['sourceId']=['in',$userList];
           }
       }elseif ($userInfo['type']==5){
           //渠道总监  1.获取总监下渠道经理列表，2.获取渠道经理下所有扩展的渠道公司id 3.生成搜索条件
            $ud=Db::name('yonghui_user')->where(['upuserid'=>$userInfo['id']])->select();
            $qdid=[];
            if($ud){
                foreach ($ud as $k=>$v){
                    $qdid[]=$v['id'];
                }
            }
            $log->info($qdid, '总监下级经理信息1');
            if($qdid){
                $com=Db::name('yonghui_company')->where(['userId'=>['in',$qdid]])->select();
                $comid=[];
                if($com){
                    foreach ($com as $k1=>$v1){
                        $comid[]=$v1['id'];
                    }
                }
                $log->info($comid, '总监下级经理信息2');
                $where['sourceId']=['in',$comid];
            }else{
                $where['sourceId']=['in',[]];
            }
           $log->info($where['sourceId'], '总监下级经理信息3');
       }elseif ($userInfo['type']==6){
           //渠道总经理助理 1.获取对应的总经理信息，2.获取总经理下的总监 3.获取总监下的渠道经理 4 获取渠道经理下的渠道公司 5.生成搜索条件
           $zonInfo=Db::name('yonghui_user')->where(['companyId'=>$userInfo['companyId'],'type'=>7])->find();
           $zojian=Db::name('yonghui_user')->where(['upuserid'=>$zonInfo['id']])->select();
           $zid=[];
           if($zojian){
               foreach ($zojian as $k=>$v){
                   $zid[]=$v['id'];
               }
           }
           $qu=Db::name('yonghui_user')->where(['upuserid'=>['in',$zid]])->select();
           $qdid=[];
           if($qu){
               foreach ($qu as $k=>$v){
                   $qdid[]=$v['id'];
               }
           }
           $com=Db::name('yonghui_company')->where(['userId'=>['in',$qdid]])->select();
           $comid=[];
           if($com){
               foreach ($com as $k1=>$v1){
                   $comid[]=$v1['id'];
               }
           }
           $where['sourceId']=['in',$comid];

       }else{
           //渠道总经理
           $zojian=Db::name('yonghui_user')->where(['upuserid'=>$userInfo['id']])->select();
           $zid=[];
           if($zojian){
               foreach ($zojian as $k=>$v){
                   $zid[]=$v['id'];
               }
           }
           $qu=Db::name('yonghui_user')->where(['upuserid'=>['in',$zid]])->select();
           $qdid=[];
           if($qu){
               foreach ($qu as $k=>$v){
                   $qdid[]=$v['id'];
               }
           }
           $com=Db::name('yonghui_company')->where(['userId'=>['in',$qdid]])->select();
           $comid=[];
           if($com){
               foreach ($com as $k1=>$v1){
                   $comid[]=$v1['id'];
               }
           }
           $where['sourceId']=['in',$comid];
       }
       $log->info($where, 'where条件');
       $log->info($order, '排序条件');
       //处理获查询条件问题
       $customerInfos=Db::name('yonghui_customer')->where($where)->order($order)
           ->field('id,name,FROM_UNIXTIME(createTime,"%Y-%m-%d %H:%i:%s") as createTime,issansi,propertiesId,inputId,followUserId,followStatus,visitTime,updateTime,gender,phone,sourceId,daofangStatus')
           ->paginate(10000, false, [
               'query' => request()->request()
           ])->toArray();
       foreach($customerInfos['data'] as $k=>$v){
           if($v['followUserId']){
               $customerInfos['data'][$k]['inputUser']=Db::name('yonghui_user')->where(['id'=>$v['followUserId']])->field('id,name')->find()['name'];
           }
           $companyInfos=Db::name('yonghui_user')->where(['id'=>$v['inputId']])->value('companyId');
           $customerInfos['data'][$k]['inputCompany']=Db::name('yonghui_company')->where(['id'=>$companyInfos])->field('id,name')->find()['name'];
           if($v['inputId']!=$userId){
               if($v['issansi']==1){
                   $customerInfos['data'][$k]['canMobile']=false;
                   $customerInfos['data'][$k]['phone'] = substr($v['phone'], 0, 3).'****'.substr($v['phone'],7);
               }else{
                   $customerInfos['data'][$k]['canMobile']=true;
               }
           }else{
               $customerInfos['data'][$k]['canMobile']=true;
           }
       }
       if($customerInfos){
           return json(['msg'=>'获取成功','code'=>'success','data'=>$customerInfos]);
       }else{
           return json(['msg'=>'未获取到数据','code'=>'success','data'=>[]]);
       }
   }
   /**
    * 录入客户  25号加手机号前三后四
    */
    public function addCustomer(){
        $data=$this->postData();
        //校验数据合法性
        if(empty($data['name'])){
            return json(['msg'=>'客户名称不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['phone'])){
            return json(['msg'=>'客户联系方式不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['propertiesId'])){
            return json(['msg'=>'客户意向楼盘id不能为空','code'=>'error','data'=>[]]);
        }
        $chars="/^1[345789]\d{9}$/";
        if (!preg_match($chars,$data['phone'])){
            return json(['msg'=>'手机号格式不正确','code'=>'error','data'=>[]]);
        }
        //判断该手机号码的客户在当前楼盘是否已经绑定，如果已经绑定判断是否购买或者已经失效
        /*$customerInfo=Db::name('yonghui_customer')->where(['propertiesId'=>$data['propertiesId'],'phone'=>$data['phone']])->find();
        if($customerInfo && $customerInfo['followStatus']==1){
            return json(['msg'=>'该客户在当前意向楼盘已经录入过，正在跟进','code'=>'error','data'=>[]]);
        }
        if($customerInfo && $customerInfo['followStatus']==3){
            return json(['msg'=>'该客户在当前意向楼盘已经录入过，已付定金','code'=>'error','data'=>[]]);
        }*/
        $customerInfo=Db::name('yonghui_customer')->where(['phone'=>$data['phone']])->find();
        if($customerInfo && $customerInfo['followStatus']==1){
            return json(['msg'=>'该客户已经录入过，正在跟进','code'=>'error','data'=>[]]);
        }
        if($customerInfo && $customerInfo['followStatus']==3){
            return json(['msg'=>'该客户已经录入过，已付定金','code'=>'error','data'=>[]]);
        }
        $luru=Db::name('yonghui_user')->where(['id'=>$data['userId']])->find();
        //只有渠道公司销售,自营公司销售可以录入客户
        if($luru['type']==1){
            return json(['msg'=>'驻场人员不能添加客户','code'=>'error','data'=>[]]);
        }
        if($luru['type']==2){
            $followId=$luru['id'];
        }else{
            $followId=0;
        }
        $insertData['name']=$data['name'];
        $insertData['phone']=$data['phone'];
        $insertData['propertiesId']=$data['propertiesId'];
        $insertData['inputId']=$data['userId'];
        $insertData['followUserId']=$followId;
        $insertData['createTime']=time();
        $insertData['sourceId']=$luru['companyId'];
        $insertData['followStatus']=1;
        $insertData['issansi']=1;
        $insert=Db::name('yonghui_customer')->insertGetId($insertData);
        if($insert){
            //给意向楼盘所属驻场发送短信
            //根据意向楼盘获取projectId
            $pro=Db::name('yonghui_building')->where(['id'=>$data['propertiesId']])->value('projectId');
            $zhiye=Db::name('yonghui_user')->where(['type'=>1,'projectId'=>$pro])->field('type,projectId,name,phone')->find();
            $this->send($zhiye['phone'],$zhiye['name']);
            return json(['msg'=>'客户添加成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'客户添加失败','code'=>'error','data'=>[]]);
    }
    /**
     * 编辑客户信息
     */
    public function editCustomer(){
        $flag=input('post.flag');
        $customerId=input('post.customerId');
        if(empty($flag)){
            return json(['msg'=>'操作类型不能为空','code'=>'error','data'=>[]]);
        }
        if($flag!='info' && $flag!='edit'){
            return json(['msg'=>'操作类型参数不正确','code'=>'error','data'=>[]]);
        }
        if(empty($customerId)){
            return json(['msg'=>'客户id不能为空','code'=>'error','data'=>[]]);
        }
        $customerInfo=Db::name('yonghui_customer')->where(['id'=>$customerId])->find();
        if($flag=='info'){
            //获取客户基本信息
            if(empty($customerInfo)){
                return json(['msg'=>'未获取到客户信息','code'=>'error','data'=>[]]);
            }
            //楼盘名称，录入人名称
            $build=Db::name('yonghui_building')->where(['id'=>$customerInfo['propertiesId']])->field('id,name')->find();
            $customerInfo['buildName']=$build['name'];
            $userInfo=Db::name('yonghui_user')->where(['id'=>$customerInfo['inputId']])->field('id,name')->find();
            $customerInfo['inputName']=$userInfo['name'];
            //获取到访凭证，签约备注，已买备注信息
            $folowInfo=Db::name('yonghui_follow')->where(['customerId'=>$customerId,'type'=>['in','2,3,4']])->order('type')->select()->toArray();
            $customerInfo['daofanginfo']=[];
            $customerInfo['qianyueinfo']=[];
            $customerInfo['yimaiinfo']=[];
            if($folowInfo){
                foreach($folowInfo as $k=>$v){
                    //var_dump(json_decode($v['imageIds'],'true'));
                    $folowInfo[$k]['imageInfo']=$this->getImageUrl(json_decode($v['imageIds'],'true'));
                    $folowInfo[$k]['createTime']=date('Y-m-d H:i:s',$v['createTime']);
                    if($v['type']==2){
                        $customerInfo['daofanginfo']=$folowInfo[$k];
                    }elseif ($v['type']==3){
                        $customerInfo['qianyueinfo']=$folowInfo[$k];
                    }else{
                        $customerInfo['yimaiinfo']=$folowInfo[$k];
                    }
                }
            }
            //$customerInfo['followInfos']=$folowInfo;
            //获取跟进信息
            $fol=Db::name('yonghui_follow')->where(['customerId'=>$customerId,'type'=>1])->order('createTime desc')->select()->toArray();
            //跟进人名称
            if($fol){
                foreach($fol as $k=>$v){
                    $fol[$k]['genjinrenname']=Db::name('yonghui_user')->where(['id'=>$v['userId']])->field('id,name')->find()['name'];
                    $fol[$k]['createTime']=date('Y-m-d H:i:s',$v['createTime']);
                }
            }
            $customerInfo['fol']=$fol;
            $customerInfo['createTime']=date('Y-m-d H:i:s',$customerInfo['createTime']);
            if($customerInfo['visitTime']){
                $customerInfo['visitTime']=date('Y-m-d H:i:s',$customerInfo['visitTime']);
            }
            if($customerInfo['inputId']!=$this->userId){
                $customerInfo['phone']=substr($customerInfo['phone'], 0, 3).'****'.substr($customerInfo['phone'],7);
                $customerInfo['canMobile']=false;
            }else{
                $customerInfo['canMobile']=true;
            }
            $companyInfos=Db::name('yonghui_user')->where(['id'=>$customerInfo['inputId']])->value('companyId');
            $customerInfo['inputCompany']=Db::name('yonghui_company')->where(['id'=>$companyInfos])->field('id,name')->find()['name'];
            return json(['msg'=>'获取成功','code'=>'success','data'=>$customerInfo]);
        }
        //驻场人员修改签约，付订状态。录入人员可以修改失效状态
        $users=Db::name('yonghui_user')->where(['id'=>$this->userId])->value('type');
        //if($users==4){
        if($users>3){
            //渠道经理  渠道总监  渠道总经理助理  渠道总经理
            return json(['msg'=>'该账号没有修改权限','code'=>'error','data'=>[]]);
        }
        $data['gender']=input('post.gender');
        if(!$data['gender']){
            return json(['msg'=>'性别参数不正确','code'=>'error','data'=>[]]);
        }
        $data['followStatus']=input('post.followStatus');
        if(!$customerInfo['followStatus']){
            return json(['msg'=>'客户状态不能为空','code'=>'error','data'=>[]]);
        }
        //判断当前客户已经属于终态（终态不能编辑）//1:跟进中 2：已失效 3：已付订 4：已签约
        if($customerInfo['followStatus']==2){
            return json(['msg'=>'该客户已失效，不能进行编辑','code'=>'error','data'=>[]]);
        }
        if($customerInfo['followStatus']==4){
            return json(['msg'=>'该客户已签约，不能进行编辑','code'=>'error','data'=>[]]);
        }
        if($data['followStatus']==1){
            $data['daofangStatus']=input('post.daofangStatus');
            //$data['daofangStatus']=1;//去掉  TODO
            if(empty($data['daofangStatus'])){
                return json(['msg'=>'到访状态参数不能为空','code'=>'error','data'=>[]]);
            }
            if($customerInfo['daofangStatus']==2){
                return json(['msg'=>'该客户已到访','code'=>'error','data'=>[]]);
            }
            $data['daofangTime']=time();
        }
        if($users==1){
            //驻场人员
            if($data['followStatus']==2){
                return json(['msg'=>'该账号没有标记失效权限','code'=>'error','data'=>[]]);
            }
            $dmoney=input('post.dmoney');
            $qmoney=input('post.qmoney');
            if($data['followStatus']==3&&empty($dmoney)){
                return json(['msg'=>'请输入订金金额','code'=>'error','data'=>[]]);
            }
            if($data['followStatus']==3||$data['followStatus']==4){
                $data['qianyueTime']=time();
            }
            if($data['followStatus']==4&&empty($qmoney)){
                return json(['msg'=>'请输入签约金额','code'=>'error','data'=>[]]);
            }
            $data['dmoney']=$dmoney;
            $data['qmoney']=$qmoney;
        }
        if($users==2){
            //置业顾问
            if($customerInfo['inputId']!=$this->userId){
                return json(['msg'=>'该账号没有修改权限','code'=>'error','data'=>[]]);
            }
            if($data['followStatus']!=2){
                return json(['msg'=>'该账号只有标记失效权限','code'=>'error','data'=>[]]);
            }
        }
        if($users==3){
            //渠道销售
            if($customerInfo['inputId']!=$this->userId){
                return json(['msg'=>'该账号不是录入人','code'=>'error','data'=>[]]);
            }
            //if($data['followStatus']!=2||$data['followStatus']!=1){
            if($data['followStatus']!=2){
                return json(['msg'=>'该账号只有标记失效权限','code'=>'error','data'=>[]]);
            }
        }
        $data['updateTime']=time();
        $upCustomer=Db::name('yonghui_customer')->where(['id'=>$customerId])->update($data);
        if($upCustomer){
            return json(['msg'=>'修改成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'修改失败','code'=>'error','data'=>[]]);
    }
    /**
     * 获取图片链接
     */
    private function getImageUrl($ids){
        $imageInfos=Db::name('upload_file')->where('file_id','in',$ids)->select();
        $arr=[];
        if($imageInfos){
            foreach($imageInfos as $k=>$v){
                $arr[]=$v['file_url'].'/'.$v['file_name'];
            }
        }
        return $arr;
    }
    /**
     * 添加客户，获取可选的意向楼盘列表
     */
    public function getLouPanList(){
        //根据当前登录用户类型 以及所属公司获取可以选择的楼盘列表
        $userInfo=Db::name('yonghui_user')->where(['id'=>$this->userId])->find();
        if($userInfo['status']==2){
            return json(['msg'=>'该用户已被禁用','code'=>'error','data'=>[]]);
        }


        if($userInfo['type']==1||$userInfo['type']==2){
            //驻场或者置业顾问
            if($userInfo['loupanids']=='all'){

            }else{
                $where['id']=['=',$userInfo['loupanids']];
            }
        }
        //根据登录人获取可以选择的楼盘  1.置业顾问获取所属项目组楼盘  2 渠道销售，获取上属自营公司所录入的全部楼盘。todo
        $com=Db::name('yonghui_company')->where(['id'=>$userInfo['companyId']])->find();
        if($com['upId']==0){
            //登录人为置业顾问，获取所属驻场人员项目组的未禁用楼盘信息
            $cid=$userInfo['companyId'];
            $projectId=$userInfo['projectId'];
        }else{
            //登录人为渠道销售人员，获取所属自营公司所添加的所有未禁用楼盘。
            $cid=$com['upId'];
        }
        if(!empty($this->postData()['search'])&&$com['upId']==0&&!in_array($userInfo['type'],[4,5,6,7])){
            $where['name']=['like','%'.$this->postData()['search'].'%'];
            $where['companyId']=['=',$cid];
            $where['projectId']=['=',$projectId];
        }elseif(!empty($this->postData()['search'])&&$com['upId']!=0){
            $where['name']=['like','%'.$this->postData()['search'].'%'];
            $where['companyId']=['=',$cid];
        }elseif(empty($this->postData()['search'])&&$com['upId']==0&&!in_array($userInfo['type'],[4,5,6,7])){
            $where['companyId']=['=',$cid];
            $where['projectId']=['=',$projectId];
        }else{
            $where['companyId']=['=',$cid];
        }
        if(in_array($userInfo['type'],[4,5,6,7])){
            $where['companyId']=['=',$cid];
        }
        $where['status']=['=',1];
        $buildList=Db::name('yonghui_building')->where($where)->field('id,name,status,companyId')->select();
        return json(['msg'=>'获取成功','code'=>'success','data'=>$buildList]);
    }

    /**
     * 到访凭证、签约备注，已买备注文件上传（图片&小文件）
     */
    public function uploadFile(){
        $fileKey = request()->file('file');
        $userInfo=Db::name('yonghui_user')->where(['id'=>$this->userId])->find();
        $res=Image::open($fileKey);
        $KeyId = $this->config['engine'][$this->config['default']]['access_key_id'];
        $KeySecret =$this->config['engine'][$this->config['default']]['access_key_secret'];
        $EndPoint = $this->config['engine'][$this->config['default']]['domain'];
        $Bucket = $this->config['engine'][$this->config['default']]['bucket'];
        $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
        $fname='客户跟进/图片/';
        $fileName = $fname. sha1(date('YmdHis', time()) . uniqid()) . '.' . $res->type();
        //执行阿里云上传
        $result = $ossClient->uploadFile($Bucket, $fileName, $fileKey->getInfo()['tmp_name']);
        $fileType =$fileKey->getInfo()['type'];
        // 信息
        $fileInfo = $fileKey->getInfo();
        $uploadFile = $this->addUploadFile(-1, $fileName, $fileInfo, $fileKey->getInfo()['name'],$fileType,$userInfo);
        // 图片上传成功
        return json(['code' => 1, 'msg' => '上传成功', 'data' => $uploadFile]);
    }
    /**
     * 添加文件库上传记录
     */
    private function addUploadFile($group_id, $fileName, $fileInfo, $old_name,$fileType,$user){
        // 存储引擎
        $storage = $this->config['default'];
        // 存储域名
        $fileUrl = isset($this->config['engine'][$storage]['domain'])?$this->config['engine'][$storage]['domain'] : '';
        // 添加文件库记录
        $model = new UploadFile;
        //记录上传图片的公司id
        $model->add([
            'group_id' => $group_id > 0 ? (int)$group_id : 0,
            'storage' => $storage,
            'file_url' => 'https://yh.globalbt.cn',
            'file_name' => $fileName,
            'is_user'=>1,
            'file_size' => $fileInfo['size'],
            'file_type' => $fileType,
            'old_name' => $old_name,
            'companyId'=> $user['companyId'],
            'extension' => pathinfo($fileInfo['name'], PATHINFO_EXTENSION),
        ]);
        return $model;
    }
    /**
     * 添加跟进信息,到访凭证、签约备注，已买备注
     */
    public function addFollowInfo(){
        $data=$this->postData();
        if(empty($data['userId'])){
            return json(['msg'=>'当前登录人id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['content'])){
            return json(['msg'=>'内容不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['customerId'])){
            return json(['msg'=>'客户id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['type'])){
            return json(['msg'=>'操作类型不能为空','code'=>'error','data'=>[]]);
        }
        $users=Db::name('yonghui_user')->where(['id'=>$data['userId']])->value('type');

        if($data['type']!=1&&$users==1){
            if(empty($data['imageIds'])){
                return json(['msg'=>'图片id参数不能为空','code'=>'error','data'=>[]]);
            }
        }
        if($data['type']!=1&&$users!=1){
            return json(['msg'=>'只有驻场人员可以编辑凭证信息','code'=>'error','data'=>[]]);
        }
        //判断当前客户状态
        $customerInfo=Db::name('yonghui_customer')->where(['id'=>$data['customerId']])->find();
        if($customerInfo&&$customerInfo['followStatus']==2){
            return json(['msg'=>'当前客户已失效','code'=>'error','data'=>[]]);
        }
        $data['imageIds']=json_encode($data['imageIds']);
        $data['createTime']=time();
        $data['updateTime']=0;
        if($customerInfo['inputId']==$this->userId){
            if(empty($data['visitTime'])&&$data['type']==1){
                return json(['msg'=>'请选择下次约访时间','code'=>'error','data'=>[]]);
            }
            $cus['visitTime']=strtotime($data['visitTime']);
        }else{
            $cus['visitTime']=0;
        }
        unset($data['token']);
        //添加跟进信息时，只有录入人可以添加下次约访时间
        if($cus['visitTime']){
            //下次约访时间据当前时间间隔1天
            if($cus['visitTime']<strtotime(date('Y-m-d',strtotime('+1 day')))){
                return json(['msg'=>'下次约访时间距离当前时间至少一天','code'=>'error','data'=>[]]);
            }
            //更新下次约访时间
            Db::name('yonghui_customer')->where(['id'=>$data['customerId']])->update(['visitTime'=>$cus['visitTime']]);
        }
        $data['visitTime']=strtotime($data['visitTime']);
        $insert=Db::name('yonghui_follow')->insertGetId($data);
        if($insert){
            return json(['msg'=>'添加成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'添加失败','code'=>'error','data'=>[]]);
    }
    /**
     * 修改跟进信息,到访凭证、签约备注，已买备注
     */
    public function editFollowInfo(){
        $data=$this->postData();
        if(empty($data['userId'])){
            return json(['msg'=>'当前登录人id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['id'])){
            return json(['msg'=>'凭证数据id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['flag'])){
            return json(['msg'=>'操作类型参数不能为空','code'=>'error','data'=>[]]);
        }
        if($data['flag']!='info'&&$data['flag']!='edit'){
            return json(['msg'=>'操作类型参数不正确','code'=>'error','data'=>[]]);
        }
        if($data['flag']=='info'){
            //获取详情数据
            $followInfo=Db::name('yonghui_follow')->where(['id'=>$data['id']])->find();
            if($followInfo['type']!=1){
                $followInfo['imageInfo']=  $this->getImageUrl(json_decode($followInfo['imageIds'],'true'));
            }else{
                $followInfo['imageInfo']=[];
                $followInfo['createTime']=date('Y-m-d H:i:s',$followInfo['createTime']);
                if($followInfo['visitTime']){
                    $followInfo['visitTime']=date('Y-m-d H:i:s',$followInfo['visitTime']);
                }else{
                    $followInfo['visitTime']=0;
                }
            }
            return json(['msg'=>'获取成功','code'=>'success','data'=>$followInfo]);
        }else{
            //修改提交数据
            $followInfos=Db::name('yonghui_follow')->where(['id'=>$data['id']])->find();
            //只有驻场人员可以修改凭证信息
            $uinfo=Db::name('yonghui_user')->where(['id'=>$this->userId])->value('type');
            if($uinfo!=1&&$followInfos['type']!=1){
                return json(['msg'=>'只有驻场人员可以编辑凭证信息','code'=>'error','data'=>[]]);
            }
            if(empty($data['content'])){
                return json(['msg'=>'内容不能为空','code'=>'error','data'=>[]]);
            }
            if($followInfos['type']!=1){
                if(empty($data['imageIds'])){
                    return json(['msg'=>'图片id参数不能为空','code'=>'error','data'=>[]]);
                }
            }
        }
        $data['imageIds']=json_encode($data['imageIds']);
        $data['updateTime']=time();
        $cus['visitTime']=strtotime($data['visitTime']);
        unset($data['flag']);
        unset($data['token']);
        /*if($cus['visitTime']){
            //下次约访时间据当前时间间隔1天
            if($cus['visitTime']<strtotime(date('Y-m-d',strtotime('+1 day')))){
                return json(['msg'=>'下次约访时间距离当前时间至少一天','code'=>'error','data'=>[]]);
            }
            //更新下次约访时间
            Db::name('yonghui_customer')->where(['id'=>$followInfos['customerId']])->update(['visitTime'=>$cus['visitTime']]);
        }*/
        $data['visitTime']=strtotime($data['visitTime']);
        $insert=Db::name('yonghui_follow')->where(['id'=>$data['id']])->update($data);
        if($insert){
            return json(['msg'=>'更新成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'更新失败','code'=>'error','data'=>[]]);
    }
    /**
     * 登录人修改头像
     */
    public function editImage(){
        $imageUrl=input('imageId');
        if(empty($imageUrl)){
            return json(['msg'=>'图片id不能为空','code'=>'error','data'=>[]]);
        }
        Db::name('yonghui_user')->where(['id'=>$this->userId])->update(['imageId'=>$imageUrl]);
        $imageIfo=Db::name('upload_file')->where(['file_id'=>$imageUrl])->find();
        return json(['msg'=>'修改成功','code'=>'success','data'=>$imageIfo['file_url'].'/'.$imageIfo['file_name']]);
    }
    /**
     * 个人中心
     */
    public function center(){
        $info=Db::name('yonghui_user')->where(['id'=>$this->userId])->field('password',true)->find();
        if(empty($info)){
            return json(['msg'=>'未获取到用户信息','code'=>'error','data'=>[]]);
        }
        if($info['status']==2){
            return json(['msg'=>'该用户已被禁用','code'=>'error','data'=>[]]);
        }
        $imageIfo=Db::name('upload_file')->where(['file_id'=>$info['imageId']])->find();
        $comapanyInfo=Db::name('yonghui_company')->where(['id'=>$info['companyId']])->field('id,name')->find();
        $info['imageUrl']=$imageIfo['file_url'].'/'.$imageIfo['file_name'];
        $info['comapnyName']=$comapanyInfo['name'];
        return json(['msg'=>'获取成功','code'=>'success','data'=>$info]);
    }
    /**
     * 短信发送
     */
    public function send($phone,$name){
        $path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
        if (file_exists($path)) {
            require_once $path;
        }
        Sms::main($phone,$name);
    }
    /**
     * 短信发送222
     */
    public function sendkehuSms(){
        $path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
        if (file_exists($path)) {
            require_once $path;
        }
        $res=Sms::mainehuSms();
        return $res;
    }
    /**
     * 驻场人员将客户指派给置业顾问
     */
    public function changeCustomer(){
        $info=Db::name('yonghui_user')->where(['id'=>$this->userId])->find();
        if($info['type']!=1){
            return json(['msg'=>'您无此操作权限','code'=>'error','data'=>[]]);
        }
        $customerId=input('post.customerId');
        $touserId=input('post.toUserId');
        if(!$touserId){
            return json(['msg'=>'指派人id不能为空','code'=>'error','data'=>[]]);
        }
        if(!$customerId){
            return json(['msg'=>'客户id不能为空','code'=>'error','data'=>[]]);
        }
        $toinfo=Db::name('yonghui_user')->where(['id'=>$touserId])->value('status');
        if($toinfo==2){
            return json(['msg'=>'该职业顾问账号已被禁用','code'=>'error','data'=>[]]);
        }
        $customerInfo=Db::name('yonghui_customer')->where(['id'=>$customerId])->find();
        if($customerInfo['followUserId']){
            return json(['msg'=>'该客户已指派给其他置业顾问','code'=>'error','data'=>[]]);
        }
        $update=Db::name('yonghui_customer')->where(['id'=>$customerId])->update(['followUserId'=>$touserId]);
        if($update){
            //给置业顾问发送短信
            $zhiye=Db::name('yonghui_user')->where(['id'=>$touserId])->find();
            $this->send($zhiye['phone'],$zhiye['name']);
            return json(['msg'=>'操作成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'操作失败','code'=>'error','data'=>[]]);
    }
    /**
     * 获取驻场人员可以指派的置业顾问列表
     */
    public function getUserList(){
        $info=Db::name('yonghui_user')->where(['id'=>$this->userId])->find();
        if($info['type']!=1){
            return json(['msg'=>'您无此操作权限','code'=>'error','data'=>[]]);
        }
        $infos=Db::name('yonghui_user')->where(['projectId'=>$info['projectId'],'type'=>2,'status'=>1,'loupanids'=>$info['loupanids']])->select();
        if($infos){
            return json(['msg'=>'获取成功','code'=>'success','data'=>$infos]);
        }
        return json(['msg'=>'未获取到信息','code'=>'error','data'=>[]]);
    }
    /**
     * 修改密码
     */
    public function updatePassword(){
         $phone=input('post.phone');
         $code=input('post.code');
         $password=input('post.password');
         $repassword=input('post.repassword');
        if (empty($phone)){
            return json(['msg'=>'手机号不能为空','code'=>'error','data'=>[]]);
        }
        if (empty($code)){
            return json(['msg'=>'验证码不能为空','code'=>'error','data'=>[]]);
        }
        if (empty($password)){
            return json(['msg'=>'新密码不能为空','code'=>'error','data'=>[]]);
        }
        if (empty($repassword)){
            return json(['msg'=>'确认密码不能为空','code'=>'error','data'=>[]]);
        }
        //手机号正则验证
        $chars = "/^1[345789]\d{9}$/";
        if(!preg_match($chars,$phone)){
            return json(['msg'=>'手机号格式不正确','code'=>'error','data'=>[]]);
        }
        $ccode=Cache::get($phone);
        if($ccode){
            if($code!=$ccode){
                return json(['msg'=>'验证码不正确','code'=>'error','data'=>[]]);
            }
        }else{
            return json(['msg'=>'验证码已过期','code'=>'error','data'=>[]]);
        }
        if($password!=$repassword){
            return json(['msg'=>'两次输入密码不一致','code'=>'error','data'=>[]]);
        }
        $update=Db::name('yonghui_user')->where(['phone'=>$phone])->update(['password'=>md5($password)]);
        if($update){
            Cache::rm($phone);
            return json(['msg'=>'密码修改成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'密码修改失败','code'=>'error','data'=>[]]);
    }
    /**
     * 发送验证码
     */
    public function sendMessage(){
        $phone=input('post.phone');
        if (empty($phone)){
            return json(['msg'=>'手机号不能为空','code'=>'error','data'=>[]]);
        }
        //手机号正则验证
        $chars = "/^1[345789]\d{9}$/";
        if(!preg_match($chars,$phone)){
            return json(['msg'=>'手机号格式不正确','code'=>'error','data'=>[]]);
        }
        $info=Db::name('yonghui_user')->where(['phone'=>$phone])->find();
        if(empty($info)){
            return json(['msg'=>'该账户不存在','code'=>'error','data'=>[]]);
        }
        $code=rand(pow(10,(6-1)), pow(10,6)-1);
        Cache::set($phone,$code,120);
        if($this->sendcode($phone,$code)==1){
            return json(['msg'=>'发送成功','code'=>'success','data'=>$code]);
        }
        Cache::rm($phone);
        return json(['msg'=>'发送失败','code'=>'error','data'=>[]]);
    }

    public function sendcode($phone,$code){
        $path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
        if (file_exists($path)) {
            require_once $path;
        }
        return Sms::codemain($phone,$code);
    }
    /**
     * 获取渠道经理下属的渠道公司列表
     */
    public function getqudaoList(){
        $userId=input('post.userId');
        //查询该用户身份和状态
        $userInfo=Db::name('yonghui_user')->where(['id'=>$userId])->find();
        if($userInfo){
            if($userInfo['type']!=4){
                return json(['msg'=>'该用户无此权限','code'=>'error','data'=>[]]);
            }
            if($userInfo['status']==2){
                return json(['msg'=>'该用户已被禁用','code'=>'error','data'=>[]]);
            }
            //获取渠道公司以及渠道公司下销售人员信息
            $companyInfo=Db::name('yonghui_company')->where(['userId'=>$userId,'type'=>2])->select()->toArray();
            //return json(['msg'=>'获取成功111','code'=>'success','data'=>$companyInfo]);
            if(!empty($companyInfo)){
                array_unshift($companyInfo,['id'=>0,'name'=>'全部','licenseId'=>0,'legalName'=>'','phone'=>'',
                'type'=>0,'upId'=>0,'updateTime'=>0,'status'=>0,'shuihao'=>'','createTime'=>'','userId'=>0]);
                foreach($companyInfo as $k=>$v){
                    if($v['id']==0){
                        $companyInfo[$k]['userList'][]=['id'=>0,'name'=>'全部'];
                    }else{
                        $userList=Db::name('yonghui_user')->where(['companyId'=>$v['id']])->select()->toArray();
                        if($userList){
                            $companyInfo[$k]['userList']=$userList;
                            array_unshift($companyInfo[$k]['userList'],['id'=>0,'name'=>'全部','password'=>0,'companyId'=>'','imageId'=>'',
                                'type'=>0,'nickName'=>0,'openId'=>0,'createTime'=>0,'updateTime'=>'','status'=>'','projectId'=>0]);
                        }else{
                            $companyInfo[$k]['userList'][]=['id'=>0,'name'=>'全部'];
                        }
                    }
                }
                return json(['msg'=>'获取成功','code'=>'success','data'=>$companyInfo]);
            }else{
                return json(['msg'=>'未获取到渠道公司信息','code'=>'error','data'=>[]]);
            }
        }else{
            return json(['msg'=>'未获取到用户信息','code'=>'error','data'=>[]]);
        }
    }
    private function get_ctime($month,$s){
         $month_start =strtotime($month) ;//指定年月份月初时间戳
         if($s=='start'){
             return $month_start;
         }
         $BeginDate=date('Y-m-01', strtotime($month));
         $EndDate = date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
         $month_end= strtotime("next day", strtotime($EndDate)) - 1;//指定年月份月末时间戳
         return $month_end;
    }

    /**
     * 渠道经理报表数据
     */
    public function qudaoexcel(){
        $userId=input('post.userId');
        $year=input('post.year');
        $month=input('post.month');
        //查询该用户身份和状态
        $userInfo=Db::name('yonghui_user')->where(['id'=>$userId])->field('id,type,status')->find();
        if($userInfo) {
            if ($userInfo['type'] != 4) {
                return json(['msg' => '该用户无此权限', 'code' => 'error', 'data' => []]);
            }
            if ($userInfo['status'] == 2){
                return json(['msg' => '该用户已被禁用', 'code' => 'error', 'data' => []]);
            }
        }
        //获取当前渠道经理扩展的所有渠道
        $companyInfo=Db::name('yonghui_company')->where(['userId'=>$userId,'status'=>1])->select()->toArray();
        //获取各个渠道公司 各种状态的客户数量
        if($companyInfo){
            $whereTime=strtotime($year.'-'.$month);
            $w['daofangTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
            $q['qianyueTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
            //1:跟进中 2：已失效 3：已付订 4：已签约
            //报备，到访，成交
            foreach ($companyInfo as $k=>$v){
                //报备
                $c['createTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
                $baobei=Db::name('yonghui_customer')->where(['sourceId'=>$v['id']])->where($c)->count();
                //到访 todo
                $daofang=Db::name('yonghui_customer')->where(['sourceId'=>$v['id'],'followStatus'=>1,'daofangStatus'=>2])->where($w)->count();
                //成交
                $chengjiao=Db::name('yonghui_customer')->where(['sourceId'=>$v['id'],'followStatus'=>['in','3,4']])->where($q)->count();
                $companyInfo[$k]['baobeicount']=$baobei;
                $companyInfo[$k]['daofangcount']=$daofang;
                $companyInfo[$k]['chengjiaocount']=$chengjiao;
            }
            return json(['msg'=>'获取成功','code'=>'success','data'=>$companyInfo]);
        }
        return json(['msg'=>'未获取到信息','code'=>'error','data'=>[]]);
    }
    /**
     * 渠道总监及以上人员报表
     */
    public function zonjianexcel(){
        $userId=input('post.userId');
        $year=input('post.year');
        $month=input('post.month');
        $loupanid=input('post.loupanid');
        //查询该用户身份和状态
        $userInfo=Db::name('yonghui_user')->where(['id'=>$userId])->field('id,type,companyId,status')->find();
        if($userInfo) {
            $array=['5','6','7'];
            if (!in_array($userInfo['type'],$array)) {
                return json(['msg' => '该用户无此权限', 'code' => 'error', 'data' => []]);
            }
            if ($userInfo['status'] == 2){
                return json(['msg' => '该用户已被禁用', 'code' => 'error', 'data' => []]);
            }
        }
        $whereTime=strtotime($year.'-'.$month);
        $c['createTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
        $w['daofangTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
        $q['qianyueTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
        //总监 5  总经理助理 6  总经理 7
        if($userInfo['type']==5){
            //获取该渠道总监下属渠道经理
            $user=Db::name('yonghui_user')->where(['upuserid'=>$userInfo['id']])->select()->toArray();
            if(!empty($loupanid)){
                $w['propertiesId']=['=',(integer)$loupanid];
            }
            $w['updateTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
            if($user){
                foreach ($user as $k=>$v){
                    //获取当前渠道公司发展的渠道公司针对某个楼盘录入的客户信息
                    $companyInfo=Db::name('yonghui_company')->where(['userId'=>$v['id'],'status'=>1])->select()->toArray();
                    $baobei=0;$daofang=0;$chengjiao=0;
                    if($companyInfo){
                        foreach($companyInfo as $k1=>$v1){
                            if($loupanid){
                                //报备
                                $baobei+=Db::name('yonghui_customer')->where(['sourceId'=>$v1['id'],'propertiesId'=>$loupanid])->where($c)->count();
                            }else{
                                //报备
                                $baobei+=Db::name('yonghui_customer')->where(['sourceId'=>$v1['id']])->where($c)->count();
                            }
                            //到访  todo
                            $daofang+=Db::name('yonghui_customer')->where(['sourceId'=>$v1['id'],'followStatus'=>1,'daofangStatus'=>2])->where($w)->count();
                            //成交
                            $chengjiao+=Db::name('yonghui_customer')->where(['sourceId'=>$v1['id'],'followStatus'=>['in','3,4']])->where($q)->count();
                        }
                    }
                    $month=intval($month);
                    $month=(string)$month;
                    if(empty($loupanid)){
                        $peizhi=Db::name('yonghui_month')->where(['year'=>$year,'month'=>$month,'userId'=>$v['id']])->sum('count');
                    }else{
                        $peizhi=Db::name('yonghui_month')->where(['year'=>$year,'month'=>$month,'loupanid'=>$loupanid,'userId'=>$v['id']])->value('count');
                        if(!$peizhi){
                            $peizhi=0;
                        }
                    }
                    $user[$k]['daikanmubiao']=$peizhi;
                    $user[$k]['baobeicount']=$baobei;
                    $user[$k]['daofangcount']=$daofang;
                    $user[$k]['chengjiaocount']=$chengjiao;
                }
                return json(['msg'=>'获取成功','code'=>'success','data'=>$user]);
            }
            return json(['msg'=>'获取成功','code'=>'success','data'=>[]]);
        }else{
            //总经理或者总经理助理  todo
            //获取该渠道总经理下属渠道总监
            if($userInfo['type']==6){
                $id=Db::name('yonghui_user')->where(['companyId'=>$userInfo['companyId'],'type'=>7])->value('id');
            }else{
                $id=$userInfo['id'];
            }
            if(!empty($loupanid)){
                $w['propertiesId']=['=',(integer)$loupanid];
            }
            $whereTime=strtotime($year.'-'.$month);
            $w['daofangTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
            $q['qianyueTime']=['between',[$whereTime,$this->get_ctime($year.'-'.$month,'end')]];
            $user=Db::name('yonghui_user')->where(['upuserid'=>$id])->select()->toArray();
            if($user){
                //获取渠道总监下的渠道经理
                foreach ($user as $k=>$v){
                    $jingli=Db::name('yonghui_user')->where(['upuserid'=>$v['id']])->field('id,name,phone,type,companyId,projectId,upuserid')->select()->toArray();
                    if($jingli){
                        foreach ($jingli as $k1=>$v1){
                            //获取当前渠道经理发展的渠道公司 针对某个楼盘 录入的客户信息
                            $companyInfo=Db::name('yonghui_company')->where(['userId'=>$v1['id'],'status'=>1])->select()->toArray();
                            $baobei=0;$daofang=0;$chengjiao=0;
                            if($companyInfo){
                                foreach($companyInfo as $k2=>$v2){
                                    if($loupanid){
                                        //报备
                                        $baobei+=Db::name('yonghui_customer')->where(['sourceId'=>$v2['id'],'propertiesId'=>$loupanid])->where($c)->count();
                                    }else{
                                        //报备
                                        $baobei+=Db::name('yonghui_customer')->where(['sourceId'=>$v2['id']])->where($c)->count();
                                    }
                                    //到访  todo
                                    $daofang+=Db::name('yonghui_customer')->where(['sourceId'=>$v2['id'],'followStatus'=>1,'daofangStatus'=>2])->where($w)->count();
                                    //成交
                                    $chengjiao+=Db::name('yonghui_customer')->where(['sourceId'=>$v2['id'],'followStatus'=>['in','3,4']])->where($q)->count();
                                }
                            }
                            $month=intval($month);
                            $month=(string)$month;
                            if(empty($loupanid)){
                                $peizhi=Db::name('yonghui_month')->where(['year'=>$year,'month'=>$month,'userId'=>$v1['id']])->sum('count');
                            }else{
                                $peizhi=Db::name('yonghui_month')->where(['year'=>$year,'month'=>$month,'loupanid'=>$loupanid,'userId'=>$v1['id']])->value('count');
                                if(!$peizhi){
                                    $peizhi=0;
                                }
                            }
                            $jingli[$k1]['daikanmubiao']=$peizhi;
                            $jingli[$k1]['baobeicount']=$baobei;
                            $jingli[$k1]['daofangcount']=$daofang;
                            $jingli[$k1]['chengjiaocount']=$chengjiao;
                        }
                    }else{
                        $jingli=[];
                    }
                    $user[$k]['jingli']=$jingli;
                }
                return json(['msg'=>'获取成功','code'=>'success','data'=>$user]);
            }else{
                return json(['msg'=>'获取失败','code'=>'error','data'=>[]]);
            }
        }
    }
}
